//
//  CarModel.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/5/14.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "CarModel.h"
#import "AFNetworking.h"
#import "InterFace.h"
#import "EncryptionData.h"
#import "ProductModel.h"
#import "CategoryModel.h"
#import "JSONKit.h"

@implementation CarModel

#pragma -mark 向服务器获取购物车信息
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{}
- (void)getCarList:(NSMutableArray *)array parameter:(NSDictionary *)parameter{
    @try {
        
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    
    NSLog(@"请求参数 ＝＝ %@",parameter);
    
    NSString *str = [self encodeString:jsonString key:PasswordKey];
    NSDictionary *paramer = @{@"sign":str};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    
    [manager POST:GetCarListInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *str = responseObject[@"sign"];
        
        
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
            [array removeAllObjects];
            NSLog(@"购物车返回结果 ＝＝＝＝ %@",dataDic);
            
            NSDictionary *myDatDic =dataDic[@"data"];
            [self setValue:myDatDic[@"AmountCanUse"] forKey:@"AmountCanUse"];
            [self setValue:myDatDic[@"DiscountPriceAmount"] forKey:@"DiscountPriceAmount"];
            [self setValue:myDatDic[@"MarketPriceAmount"] forKey:@"MarketPriceAmount"];
            [self setValue:myDatDic[@"Amount"] forKey:@"Amount"];
            NSArray *myDatArr = myDatDic[@"CartInfo"];
            //
            for (int i = 0; i <[myDatArr count]; i++) {
                //
                NSDictionary *productDic = myDatArr[i];
                CarModel *model = [[CarModel alloc] init];
                //
                [model setValuesForKeysWithDictionary:productDic];
                //
                [array addObject:model];
            }
            [self.carModelDelegate getCarListEnd];
        } else if([dataDic[@"reason"] isEqualToString:@"暂无数据"]){
            
            [self.carModelDelegate getCarListEnd];

        }
        else{
            [self.carModelDelegate getCarListEnd];
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:dataDic[@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
#warning - 注释掉这个更新购物车树目的委托
//            [self.carModelDelegate getrequesterror:dataDic[@"reason"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [self.carModelDelegate getCarListEnd];
//        NSLog(@"========== %@", [error description]);
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
        [self.carModelDelegate requesterror];
    }];
    }
    @catch (NSException *exception) {
        NSLog(@"获取购物车信息抛出异常 ===== %@", [exception userInfo]);
    }
}

#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}
@end
